package com.basic.business.common.token;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.basic.business.common.constants.KmConstants;
import com.basic.business.common.utils.kmUtil.PostParamsUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 刷新token 30天内必须刷新，否则需要联系快麦平台手动刷新
 */
@Slf4j
public class TokenUtils {

    private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    public static void init() {
        executor.scheduleAtFixedRate(TokenUtils::refresh, 1, 2, TimeUnit.DAYS);
    }

    private static void refresh() {
        String result = HttpUtil.post(KmConstants.URL, JSON.toJSONString(PostParamsUtil.getRefreshTokenParams()));
        JSONObject jsonObject = JSONObject.parseObject(result);
        boolean success = jsonObject.getBoolean("success");
        if (!success && !jsonObject.getString("code").equals("refresh_frequently")) {
            log.error("【~~~刷新token失败~~~】，错误信息-->{}", jsonObject.getString("msg"));
        } else {
            log.info("【~~~刷新token成功~~~】");
        }
    }
}
